package com.zbkj.common.utils.qweather;

import cn.hutool.http.HttpUtil;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.Security;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.Base64;

public class QweatherUtil {

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    public static void postJson(String jwt) {
        String url = "https://pd6hewtwfd.re.qweatherapi.com/v7/weather/now?location=101010100";
        String Data = "";
        String rsp = HttpUtil.createPost(url)//
                .header("Authorization", "Bearer " + jwt)//
//                .header("typ", "JWT")//
//                .header("Action", Action)//
//                .body(Data, "text/plain")//
                .execute().body();
        System.out.println("rsp = " + rsp);
    }

    public static String toGet(String jwt, String location) {
        // 传经纬度调用
        String url = "https://pd6hewtwfd.re.qweatherapi.com/v7/weather/now?location=" + location;
        String rsp = HttpUtil.createGet(url)//
                .header("Authorization", "Bearer " + jwt)
//                .header("typ", "JWT")//预留
                .execute().body();
//        System.out.println("rsp = " + rsp);
        return rsp;
    }

    public static String pullData(String location) {
        // 示例：Ed25519 私钥（PKCS#8 格式，Base64 编码）
        // 注意：这是示例私钥，请勿在生产环境使用
        String encodedPrivateKey = "MC4CAQAwBQYDK2VwBCIEIFaN+ZSkQUPZR0ZK6wFt2qgqSRsBYew2tNqKgwNwVHkT";

        // 要签名的数据
        String data1 = "Hello, EdDSA!";
        byte[] dataBytes = data1.getBytes();

        try {
            // 1. 解码 Base64 私钥
            byte[] privateKeyBytes = Base64.getDecoder().decode(encodedPrivateKey);

            // 2. 构造 PKCS8EncodedKeySpec
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);

            // 3. 使用 Bouncy Castle 的 KeyFactory 生成私钥
            KeyFactory keyFactory = KeyFactory.getInstance("EdDSA", "BC");
            PrivateKey privateKey = keyFactory.generatePrivate(keySpec);


            // Header
            String headerJson = "{\"alg\": \"EdDSA\", \"kid\": \"TBPQJJEDNK\"}";

            // Payload
            long iat = ZonedDateTime.now(ZoneOffset.UTC).toEpochSecond() - 30;
            long exp = iat + 900;
            String payloadJson = "{\"sub\": \"44TQH7R5RY\", \"iat\": " + iat + ", \"exp\": " + exp + "}";

            // Base64url header+payload
            String headerEncoded = Base64.getUrlEncoder().encodeToString(headerJson.getBytes(StandardCharsets.UTF_8));
            String payloadEncoded = Base64.getUrlEncoder().encodeToString(payloadJson.getBytes(StandardCharsets.UTF_8));
            String data = headerEncoded + "." + payloadEncoded;

//            EdDSANamedCurveSpec spec = EdDSANamedCurveTable.getByName(EdDSANamedCurveTable.ED_25519);

            // Sign
//            final Signature s = new EdDSAEngine(MessageDigest.getInstance(spec.getHashAlgorithm()));
            // 4. 创建签名对象（算法：Ed25519）
            Signature s = Signature.getInstance("Ed25519", "BC");

            // 5. 初始化签名（使用私钥）
            s.initSign(privateKey);

            // 6. 更新要签名的数据
            s.update(dataBytes);

            // 7. 生成签名
            byte[] sigBytes = s.sign();

            // 8. 输出 Base64 编码的签名
            String signatureBase64 = Base64.getEncoder().encodeToString(sigBytes);
            System.out.println("签名结果: " + signatureBase64);

            s.initSign(privateKey);
            s.update(data.getBytes(StandardCharsets.UTF_8));
            byte[] signature = s.sign();

            String signatureString = Base64.getUrlEncoder().encodeToString(signature);

            System.out.println("Signature: \n" + signatureString);

            // Print Token
            String jwt = data + "." + signatureString;
            System.out.println("JWT: \n" + jwt);
            return toGet(jwt, location);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
